// 导入数据库连接模块
const db = require('../db/index.js')
// 导入bcrypt加密中间件（当前未使用，可能为其他功能预留）
const bcrypt = require('bcrypt')
// 导入node.js的crypto库生成uuid
const crypto = require('crypto')
// 导入fs模块用于文件系统操作
fs = require('fs')

// 上传头像的接口处理函数
exports.uploadAvatar = (req, res) => {
    // 使用crypto生成唯一标识（UUID）
    const onlyId = crypto.randomUUID()

    // 获取上传文件的临时文件名（由multer等中间件生成）
    let oldName = req.files[0].filename;

    // 处理原始文件名编码转换（解决中文文件名乱码问题）
    // 从latin1编码转换为utf8
    // 当文件名中包含中文时，会出现报错，因为无需转换，此时，将from里的encoding参数设置为utf8即可
    let newName = Buffer.from(req.files[0].originalname, 'latin1').toString('utf8')

    // 将临时文件移动到目标目录并重命名为原始文件名
    // 注意：直接使用原始文件名可能导致文件覆盖
    fs.renameSync('./public/upload/' + oldName, './public/upload/' + newName)

    // 准备SQL插入语句，使用set语法动态设置字段
    const sql = 'insert into image set ?'

    // 执行数据库插入操作
    db.query(sql, {
        image_url: `http://127.0.0.1:3030/upload/${newName}`, // 完整的图片访问URL
        onlyId // 绑定生成的UUID
    }, (err, result) => {
        // 如果发生错误，使用自定义错误处理函数返回错误信息
        if (err) return res.cc(err)

        // 返回成功响应，包含唯一标识和图片访问URL
        res.send({
            onlyId,
            status: 0, // 0表示成功
            url: 'http://127.0.0.1:3030/upload/' + newName
        })
    })
}

//头像绑定账号
exports.avatarBindAccount = (req, res) => {
    const {account, onlyId, url} = req.body
    const sql1 = 'update image set account = ? where onlyId = ?'
    db.query(sql1, [account, onlyId], (err, result) => {
        if (err) return res.cc(err);
        if (result.affectedRows === 1) {
            const sql2 = 'update users set image_url = ? where account = ?'
            db.query(sql2, [url, account], (err, result) => {
                if (err) return res.cc(err);
                res.send({
                    status: 0,
                    message: '头像绑定成功'
                })
            })
        }
    })
}

//获取用户信息
exports.getUserInfo = (req, res) => {
    const sql = 'select * from users where id = ?'
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.cc(err);
        result[0].password = ''
        //返回用户信息
        res.send({
            status: 0,
            message: '获取用户信息成功!',
            results: result[0]
        });
    })
}

//修改姓名
exports.changeName = (req, res) => {
    const {id, name} = req.body
    const sql = 'update users set name = ? where id = ?'
    db.query(sql, [name, id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '修改姓名成功'
        })
    })
}

//修改性别
exports.changeSex = (req, res) => {
    const {id, sex} = req.body
    const sql = 'update users set sex = ? where id = ?'
    db.query(sql, [sex, id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '修改性别成功'
        })
    })
}

//修改邮箱
exports.changeEmail = (req, res) => {
    const {id, email} = req.body
    const sql = 'update users set email = ? where id = ?'
    db.query(sql, [email, id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '修改邮箱成功'
        })
    })
}

//修改密码
//首先判断旧密码是否匹配原密码,然后再更新
exports.changePassword = (req, res) => {
    const {id, oldPassword} = req.body
    const sql1 = 'select password from users where id = ?'
    //使用[]包裹id，防止sql注入攻击
    db.query(sql1, [id], (err, result) => {
        if (err) return res.cc(err);
        const compareResult = bcrypt.compareSync(oldPassword, result[0].password);
        //如果原密码不匹配,返回错误,不使用return会继续执行,将会导致重复设置status
        if (!compareResult) {
            return res.send({
                status: 1,
                message: '原密码错误'
            })
        }
        req.body.newPassword = bcrypt.hashSync(req.body.newPassword, 10)
        const sql2 = 'update users set password = ? where id = ?'
        db.query(sql2, [req.body.newPassword, id], (err, result) => {
            if (err) return res.cc(err);
            res.send({
                status: 0,
                message: '修改密码成功'
            })
        })
    })
}

//登陆页面验证邮箱和账号
exports.verifyAccountAndEmail = (req, res) => {
    const {email, account} = req.body
    const sql = 'select * from users where account = ?'
    db.query(sql, [account], (err, result) => {
        if (err) return res.cc(err);
        if (result[0].email === email) {
            return res.send({
                status: 0,
                message: '邮箱和账号匹配',
                id: result[0].id
            })
        } else {
            return res.send({
                status: 1,
                message: '邮箱和账号不匹配'
            })
        }
    })
}

//登陆页面忘记密码->修改密码功能
exports.changePasswordInLogin = (req, res) => {
    req.body.newPassword = bcrypt.hashSync(req.body.newPassword, 10);
    const sql = 'update users set password = ? where id = ?'
    db.query(sql, [req.body.newPassword, req.body.id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '更新密码成功'
        })
    })
}

//以下接口是对用户权限的管理
//创建管理员
exports.createAdmin = (req, res) => {
    const {
        account,
        password,
        sex,
        name,
        email,
        department,
        identity
    } = req.body
    const sql = 'select * from users where account = ?'
    db.query(sql, [account], (err, result) => {
        if (err) return res.cc(err);
        if (result.length > 0) {
            return res.send({
                status: 1,
                message: '该账号已存在'
            })
        } else {
            req.body.password = bcrypt.hashSync(password, 10)
            const sql2 = 'insert into users set ?'
            const create_time = new Date()
            db.query(sql2, {
                account,
                password: req.body.password,
                name,
                sex,
                email,
                department,
                identity,
                create_time,
                status: 0
            }, (err, result) => {
                if (err) return res.cc(err);
                if (result.affectedRows !== 1) {
                    return res.send({
                        status: 1,
                        message: '创建管理员失败'
                    })
                } else {
                    return res.send({
                        status: 0,
                        message: '创建管理员成功'
                    })
                }
            })
        }
    })
}

//获取管理员
exports.getAdmin = (req, res) => {
    const sql = 'select * from users where identity =?'
    db.query(sql, [req.body.identity], (err, result) => {
        if (err) return res.cc(err);
        result.forEach(item => {
            item.password = ''
        })
        res.send(result)
    })
}
//编辑管理员信息
exports.editAdmin = (req, res) => {
    const {id, name, sex, email, department,identity} = req.body;
    const update_time = new Date();
    const sql0 = 'select department from users where id = ?'
    db.query(sql0, [id], (err, result) => {
        if (err) return res.cc(err);
        if (result[0].department === department) {
            const sql = 'update users set identity = ?, name = ?, sex = ?, email = ?, department = ?, update_time = ? where id = ?';
            db.query(sql, [identity,name, sex, email, department, update_time, id], (err, result) => {
                if (err) return res.cc(err);
                res.send({
                    status: 0,
                    message: '编辑管理员信息成功'
                });
            });
        }else{
            const sql = 'update users set identity = ?, name = ?, sex = ?, email = ?, department = ?, update_time = ? ,read_list = null,read_status = 0 where id = ?';
            db.query(sql, [identity,name, sex, email, department, update_time, id], (err, result) => {
                if (err) return res.cc(err);
                res.send({
                    status: 0,
                    message: '编辑管理员信息成功'
                });
            });
        }
    })
};
//修改管理员身份
exports.changeIdentity = (req, res) => {
    const {id, identity} = req.body;
    const update_time = new Date();
    const sql = 'update users set identity = ?,update_time = ? where id = ?';
    db.query(sql, [identity, update_time, id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '修改身份成功'
        });
    });
}

//通过账号和身份搜索用户
exports.searchUser = (req, res) => {
    const {account, identity} = req.body
    const sql = 'select * from users where account = ? and identity in (?)'
    db.query(sql, [account, identity], (err, result) => {
        if (err) return res.cc(err);
        result.forEach(item => {
            item.password = ''
        })
        res.send(result)
    })
}

//解冻或者冻结用户
exports.controlStatus = (req, res) => {
    const {status, id} = req.body
    const sql = 'update users set status = ? where id = ?'
    db.query(sql, [status, id], (err, result) => {
        if (err) return res.cc(err);
        res.send({
            status: 0,
            message: '修改状态成功'
        })
    })
}

//获取冻结用户列表
exports.getFrozenUser = (req, res) => {
    const sql = 'select * from users where status = 1'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err);
        res.send(result)
    })
}

//删除用户
exports.deleteUser = (req, res) => {
    const {id, account} = req.body
    const sql = 'delete from users where id =?'
    db.query(sql, [id], (err, result) => {
        if (err) return res.cc(err);
        const sql2 = 'delete from image where account = ?'
        db.query(sql2, [account], (err, result) => {
            if (err) return res.cc(err);
            res.send({
                status: 0,
                message: '删除用户成功'
            })
        })
    })
}

//通过部门获取用户
exports.getUserByDepartment = (req, res) => {
    const {department} = req.body
    const sql = 'select * from users where department =? and identity = "用户"'
    db.query(sql, [department], (err, result) => {
        if (err) return res.cc(err);
        result.forEach(item => {
            item.password = ''
        })
        res.send(result)
    })
}

//获取对应身份用户的长度
exports.getUserLength = (req, res) => {
    const sql = 'select count(*) as count from users where identity in (?)'
    db.query(sql, [req.body.identity], (err, result) => {
        if (err) return res.cc(err);
        res.send(result)
    })
}

//监听分页查询用户信息
exports.getUserListByPage = (req, res) => {
    const {page, identity} = req.body;
    const pageSize = 10; // 可配置的分页大小
    const offset = (page - 1) * pageSize;

    // 查询总数
    const countSql = 'select count(*) as total from users where identity in (?)';
    const dataSql = 'select * from users where identity in (?) limit ? offset ?';

    // 先查询总数
    db.query(countSql, [identity], (err, countResult) => {
        if (err) return res.cc(err);

        // 查询分页数据
        db.query(dataSql, [identity, pageSize, offset], (err, result) => {
            if (err) return res.cc(err);

            result.forEach(item => {
                item.password = '';
            });

            res.send({
                status: 0,
                data: result,
                total: countResult[0].total,
                pageSize,
                currentPage: page
            });
        });
    });
}